﻿using DotNetExtensions.Core.Logging;
using DotNetExtensions.Core.Restful;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace DotNetExtensions.Core.WebApi.Filters
{
    public class GlobalExceptionFilter : IAsyncExceptionFilter
    {
        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (context.ExceptionHandled == false)
            {
                // 定义返回类型
                if (context.Exception != null)
                {
                    ILogger logger = LoggerManager.GetLogger("GlobalException");
                    logger.LogError($"[500] [Http Request Url] {context.HttpContext.Request.Path} [Message] {context.Exception.Message} [StackTrace]{context.Exception.StackTrace}");
                }
                var result = ApiResult.Failed(context.Exception?.Message);
                context.Result = new ContentResult
                {
                    StatusCode = StatusCodes.Status200OK,
                    ContentType = "application/json;charset=utf-8",
                    Content = JsonConvert.SerializeObject(result, new JsonSerializerSettings
                    {
                        ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
                    })
                };
            }
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }
}
